<!-- ERC-物资类型-物资种类页面 -->
<template>
  <div>
    <div class="equip-wrap-common">
      <!--左侧树形结构 -->
      <div class="equip-tree-wrap">
        <div class="equip-tree-content">
          <px-input v-model="filterText" style="margin-right: 6px" placeholder="请输入关键字搜索" />
          <px-tooltip content="新增物资种类" placement="top">
            <px-button
              v-has="'ERC_MATERIAL_TYPE_ADDTREETOP'"
              style="margin-left: 4px"
              link
              type="primary"
              icon="AddRectangle"
              @click="AddTree('add')"
            />
          </px-tooltip>
          <px-tooltip content="全部收折" placement="top">
            <px-button v-show="isTreeOpen" style="margin-left: 4px" link type="primary" icon="ChevronUpRectangle" @click="openOrCloseTree('close')" />
          </px-tooltip>
          <px-tooltip content="全部展开" placement="top">
            <px-button
              v-show="!isTreeOpen"
              style="margin-left: 4px"
              link
              type="primary"
              icon="ChevronDownRectangle"
              @click="openOrCloseTree('open')"
            />
          </px-tooltip>
          <px-tooltip content="清除选中" placement="top">
            <px-button style="margin-left: 4px" link type="primary" icon="RefreshLeft" @click="resetCheck" />
          </px-tooltip>
        </div>
        <px-scrollbar class="equip-scroll">
          <px-tree
            ref="treeRef"
            :data="treeData"
            :props="{ children: 'children', label: 'name' }"
            default-expand-all
            node-key="id"
            :filter-node-method="filterNode"
            :expand-on-click-node="false"
            highlight-current
            :expanded-keys="expandedKeys"
            @node-click="nodeClick"
          >
            <template #default="{ node, data }">
              <span style="display: flex; align-items: center; height: 100%" class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span style="position: relative; display: inline-block">
                  <px-dropdown trigger="click">
                    <px-button
                      v-or="['ERC_MATERIAL_TYPE_ADDTREE', 'ERC_MATERIAL_TYPE_EDITTREE', 'ERC_MATERIAL_TYPE_DELETETREE']"
                      link
                      type="primary"
                      icon="More"
                      @click.stop="showDropdown(data)"
                    />
                    <template #dropdown>
                      <px-dropdown-menu>
                        <div v-if="leftTypeLevel !== 3" v-has="'ERC_MATERIAL_TYPE_ADDTREE'">
                          <px-dropdown-item @click="AddTree(data)">
                            <px-icon> <Plus /> </px-icon><span>新增</span></px-dropdown-item
                          >
                        </div>
                        <div v-has="'ERC_MATERIAL_TYPE_EDITTREE'">
                          <px-dropdown-item @click="EditTree(data)"
                            ><px-icon> <EditPen /> </px-icon><span>编辑</span></px-dropdown-item
                          >
                        </div>
                        <div v-has="'ERC_MATERIAL_TYPE_DELETETREE'">
                          <px-dropdown-item @click="DeleteTree(data)"
                            ><px-icon> <Delete /> </px-icon><span>删除</span></px-dropdown-item
                          >
                        </div>
                      </px-dropdown-menu>
                    </template>
                  </px-dropdown>
                </span>
              </span>
            </template>
          </px-tree>
        </px-scrollbar>
      </div>
      <!-- 右侧整体功能 -->
      <div class="equip-table-wrap">
        <!-- 搜索功能 -->
        <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
          <px-row :gutter="16">
            <px-col :span="5">
              <px-form-item label="物资名称">
                <px-input
                  v-model="queryParams.name"
                  placeholder="请输入名称"
                  maxlength="50"
                  @blur="queryParams.value = $event.target.value.trim()"
                  @keyup.enter="queryTable"
                >
                  <template #suffix>
                    <px-icon style="cursor: pointer" @click="queryTable">
                      <search />
                    </px-icon>
                  </template>
                </px-input>
              </px-form-item>
            </px-col>
            <px-col :span="5">
              <px-form-item label="物资编码">
                <px-input
                  v-model="queryParams.code"
                  placeholder="请输入编码"
                  maxlength="50"
                  @blur="queryParams.value = $event.target.value.trim()"
                  @keyup.enter="queryTable"
                >
                  <template #suffix>
                    <px-icon style="cursor: pointer" @click="queryTable">
                      <search />
                    </px-icon>
                  </template>
                </px-input>
              </px-form-item>
            </px-col>
            <px-col :span="4">
              <px-button type="primary" @click="queryTable">查询</px-button>
              <px-button @click="resetTable">重置</px-button>
            </px-col>
          </px-row>
        </px-form>
        <!-- 按钮功能 -->
        <div class="equip-table-btn">
          <px-button v-has="'ERC_MATERIAL_TYPE_ADD'" :disabled="typeLevel == ''" style="margin-right: 8px" type="primary" @click="addTableType"
            >新增物资</px-button
          >
          <px-button v-has="'ERC_MATERIAL_TYPE_BATCHDELETE'" type="primary" plain @click="batchDelete">批量删除</px-button>
          <px-button v-has="'ERC_MATERIAL_TYPE_BATCHDOWNLOAD'" style="margin-right: 8px; margin-left: 8px" type="primary" plain @click="batchDownload"
            >导出</px-button
          >
          <px-button
            v-has="'ERC_MATERIAL_TYPE_BATCHDOWNLOADIMG'"
            type="primary"
            :disabled="typeLevel == '' && selectIds.length == 0"
            style="margin-right: 8px"
            plain
            @click="batchDownloadEqpImg"
          >
            查询并导出种类标签
          </px-button>
          <px-button v-has="'ERC_MATERIAL_TYPE_RECREATE'" type="primary" style="margin-right: 8px" plain @click="isEqpImgShow = true"
            >种类标签重新生成</px-button
          >
        </div>
        <!-- 表格功能 -->
        <px-table
          :data="tableData"
          class="equip-table"
          size="small"
          height="calc(100vh - 304px)"
          scrollbar-always-on
          border
          @selection-change="selectionChange"
        >
          <px-table-column type="selection" min-width="40" align="center" fixed="left" />
          <px-table-column label="序号" min-width="60" align="center" fixed="left">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>
          <px-table-column
            v-for="(item, index) in tableColumns"
            :key="index"
            :label="item.label"
            :min-width="item.minWidth"
            :align="item.align"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :fixed="item.fixed"
          >
            <template #default="scope">
              <px-button v-if="item.name" link type="primary" @click="handleView(scope.row)">
                {{ scope.row.name }}
              </px-button>
              <span v-else-if="item.code">
                <span> {{ scope.row.code }} </span>
              </span>
              <span v-else> {{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
            </template>
          </px-table-column>
          <px-table-column fixed="right" label="操作" min-width="180" align="center">
            <template #default="scope">
              <px-tooltip content="详情" placement="top">
                <px-button v-has="'ERC_MATERIAL_TYPE_VIEW'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
              </px-tooltip>
              <px-tooltip content="编辑" placement="top">
                <px-button v-has="'ERC_MATERIAL_TYPE_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
              </px-tooltip>
              <px-tooltip content="复制" placement="top">
                <px-button v-has="'ERC_MATERIAL_TYPE_COPY'" link type="primary" icon="DocumentCopy" @click="handleCopy(scope.row)" />
              </px-tooltip>
              <px-tooltip content="删除" placement="top">
                <px-button v-has="'ERC_MATERIAL_TYPE_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          class="equip-pagination"
          :total="total"
          @pagination="queryTable"
        />
      </div>
    </div>
    <!-- 左侧添加树类型页面 -->
    <AddTreeDetail
      :TreedialogVisible="TreedialogVisible"
      :dialogType="dialogType"
      :dialogRow="dialogRow"
      @queryTable="queryTable"
      @queryTree="queryTree"
      @closeDialog="TreedialogVisible = false"
    />
    <!-- 右侧设备类型新增/编辑页面 -->
    <AddTypeDetail
      :dialogVisible="dialogVisible"
      :dialogType="dialogType"
      :rowData="rowData"
      :treeDataList="treeDataList"
      source="runRecord"
      @queryTable="queryTable"
      @closeDialog="closeDialog"
    />
    <!-- 详情详情页面 -->
    <ViewTypeDetail
      :dialogVisible="dialogVisibleView"
      :dialogType="dialogType"
      :rowData="rowData"
      :treeDataList="treeDataList"
      source="runRecord"
      @queryTable="queryTable"
      @closeDialog="closeDialog"
    />
    <!--种类标签批量生成弹窗-->
    <CreateEqpImgDialog :visible="isEqpImgShow" @closeDialog="isEqpImgShow = false" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ERC_SPAREPARTS_LEDGER"
});
import { onMounted, reactive, toRefs, watch, getCurrentInstance } from "vue";
import BatchUpload from "@/components/Upload/BatchUpload.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { queryDictData } from "@/api/common"; //设备状态接口
import AddTreeDetail from "./components/AddTreeDetail.vue";
import AddTypeDetail from "./components/AddTypeDetail.vue";
import ViewTypeDetail from "./components/ViewTypeDetail.vue";
import CreateEqpImgDialog from "./components/CreateEqpImgDialog.vue";
import { searchTreeMaterial, deleteTreeMaterial, queryToolMaterial, deleteToolMaterial, getEqpImgs } from "@/api/erc/material";
import axios from "axios";
import { getToken } from "@/utils/auth";

const { proxy }: any = getCurrentInstance();
const state = reactive<any>({
  parentCode: "",
  leftTypeLevel: "", //左侧树新增按钮隐藏显示
  typeLevel: "", //右侧新增按钮隐藏显示
  filterText: "",
  treeRef: null,
  treeData: [],
  expandedKeys: [],
  isTreeOpen: true,
  TreedialogVisible: false,
  dialogRow: {},
  facCodeList: [],
  positionCodeList: [],
  eqpStatusList: [],
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    facCode: "",
    name: "",
    code: ""
  },
  formValue: {
    eqpId: "",
    eqpName: "",
    facCode: "",
    facName: "",
    typeCode: "",
    positionCode: ""
  },
  treeDataPlus: "",
  tableColumns: [
    { prop: "name", label: "物资名称", minWidth: "120", showOverflowTooltip: true, name: true, fixed: "left" },
    { prop: "typeNameAll", label: "物资类型", minWidth: "80", showOverflowTooltip: true },
    { prop: "code", label: "物资编码", minWidth: "120", showOverflowTooltip: true, code: true },
    { prop: "brand", label: "品牌", minWidth: "80", showOverflowTooltip: true },
    { prop: "specification", label: "规格型号", minWidth: "80", showOverflowTooltip: true },
    { prop: "unit", label: "单位", minWidth: "80", showOverflowTooltip: true },
    { prop: "safeStock", label: "安全库存", minWidth: "80", showOverflowTooltip: true },
    { prop: "createByName", label: "创建人", minWidth: "120", showOverflowTooltip: true },
    { prop: "createTime", label: "创建时间", minWidth: "120", showOverflowTooltip: true },
    { prop: "remark", label: "备注", minWidth: "80", showOverflowTooltip: true }
  ],
  tableData: [],
  total: 0,
  selectIds: [],
  bigFileLists: [],
  eqpIdLists: [],
  downloadParams: {
    ids: [],
    systemCode: "",
    facCode: "",
    value: "",
    positionCode: "",
    eqpStatus: ""
  },
  rowData: {},
  treeDataList: {},
  dialogType: "add",
  dialogVisible: false,
  dialogVisibleView: false,
  viewDialogVisible: false,
  typeCode: "",
  isEqpImgShow: false
});
const {
  filterText,
  parentCode,
  leftTypeLevel,
  typeLevel,
  treeRef,
  treeData,
  treeDataList,
  expandedKeys,
  isTreeOpen,
  TreedialogVisible,
  dialogRow,
  facCodeList,
  queryParams,
  tableColumns,
  tableData,
  total,
  selectIds,
  bigFileLists,
  eqpIdLists,
  dialogType,
  dialogVisible,
  dialogVisibleView,
  rowData,
  viewDialogVisible,
  typeCode,
  isEqpImgShow
} = toRefs(state);

// 监视过滤树的值
watch(filterText, val => {
  treeRef.value!.filter(val);
});

// 进入页面时触发
onMounted(() => {
  queryTree();
  queryTable();
});

/** 左侧-树形区 **/
// 进入页面加载左侧树
const queryTree = async () => {
  const data: any = await searchTreeMaterial({
    name: ""
  });
  treeData.value = data;
};
// 过滤树数据
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};
// 左侧树添加清除选中按钮
const resetCheck = () => {
  filterText.value = "";
  const selectedNodes = document.querySelectorAll(".is-current");
  selectedNodes.forEach(element => {
    element.classList.remove("is-current");
  });
  queryParams.value = {
    pageNum: 1,
    pageSize: 20,
    facCode: queryParams.value.facCode,
    name: queryParams.value.name,
    code: queryParams.value.code
  };
  queryTable();
};
// 点击左侧树节点，获取facCode，查询设备列表
const nodeClick = (data, node) => {
  typeCode.value = data.parentCode;
  treeDataList.value = data;
  queryParams.value.typeCode = data.path;
  typeLevel.value = data.typeLevel;
  queryTable();
};
// 打开或者关闭树
const openOrCloseTree = type => {
  if (type == "close") {
    isTreeOpen.value = false;
    let nodes = treeRef.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = false;
    });
  } else if (type == "open") {
    isTreeOpen.value = true;
    let nodes = treeRef.value.store._getAllNodes();
    nodes.forEach(item => {
      item.expanded = true;
    });
  }
};

const showDropdown = data => {
  parentCode.value = data.parentCode;
  leftTypeLevel.value = data.typeLevel;
};
// 新增树形类型
const AddTree = data => {
  dialogType.value = "add";
  TreedialogVisible.value = true;
  dialogRow.value = data;
};
// 编辑树形类型-显示弹窗
const EditTree = data => {
  dialogType.value = "edit";
  dialogRow.value = data;
  TreedialogVisible.value = true;
};
// 删除树形类型
const DeleteTree = async (data: any) => {
  PxMessageBox.confirm(`确定要删除当前物资类型“${data.name}”吗？`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const params = {
        code: data.code,
        parentCode: data.parentCode || 0
      };
      await deleteTreeMaterial(params);
      PxMessage.success("删除成功");
      queryTable();
      queryTree();
    })
    .catch(() => {});
};
/** 右侧-表格区 **/
// 关闭弹窗
const closeDialog = () => {
  dialogVisibleView.value = false;
  dialogVisible.value = false;
  viewDialogVisible.value = false;
};
// 详情设备
// 查询物资管理列表
const queryTable = async () => {
  const data = await queryToolMaterial({ ...queryParams.value });
  tableData.value = data?.data;
  total.value = data?.total;
};
// 重置筛选条件和物资管理列表
const resetTable = async () => {
  queryParams.value.name = "";
  queryParams.value.code = "";
  queryParams.value.facCode = "";
  queryTable();
};
// 按钮功能
// 新增物资管理按钮
const addTableType = () => {
  dialogType.value = "add";
  dialogVisible.value = true;
};
// 下载模版按钮
const templateDownload = async () => {
  proxy.download("get", "/erc/api/v1/eqp/templateDownLoad", {}, "设备管理设备台账信息模板.xlsx");
};
// 表格多选框选中-批量导出、批量删除使用
const selectionChange = (val: any) => {
  selectIds.value = [];
  eqpIdLists.value = [];
  bigFileLists.value = [];
  val.forEach((item: any) => {
    if (item.id) {
      selectIds.value.push(item.id);
      eqpIdLists.value.push(item.id);
      bigFileLists.value.push(item.bigFile);
    }
  });
};
// 批量导出按钮
const batchDownload = async () => {
  await queryTable();
  const params = queryParams.value;
  proxy.download("post", "/erc/api/v1/material/exportMaterialData", params, "物资种类台账信息.xlsx");
};
// 批量删除按钮
const batchDelete = async () => {
  if (eqpIdLists.value.length == 0) {
    PxMessage.warning("请选择设备后操作");
    return;
  }
  PxMessageBox.confirm(`要删除当前已选的 ${eqpIdLists.value.length} 个物资吗？删除后不可恢复，请谨慎操作`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const data = await deleteToolMaterial({
        idList: eqpIdLists.value
      });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
// 批量下载设备图片
const batchDownloadEqpImg = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  const { positionCodes } = queryParams.value;
  params.typeCode = queryParams.value.typeCode;
  const eqpImgIdList: any = await getEqpImgs({ ...params, positionCodes: positionCodes ? [positionCodes[positionCodes?.length - 1]] : [] });
  if (eqpImgIdList.length !== 0) {
    axios({
      method: "post",
      url: "/ifp/sharing/api/v1/file/downloadFilesAsZip",
      data: {
        factoryId: queryParams.value.facCode,
        // idList: eqpImgIdList
        idList: bigFileLists.value && bigFileLists.value.length > 0 ? bigFileLists.value : eqpImgIdList
      },
      responseType: "blob",
      headers: {
        Accept: "application/json, text/plain, */*",
        "Content-Type": "application/json",
        "X-Requested-With": "XMLHttpRequest",
        Authorization: "Bearer " + (getToken().accessToken || "")
      }
    }).then(async res => {
      const blob = new Blob([res.data], { type: res.headers["content-Type"] });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = "物资种类.zip";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    });
  } else {
    PxMessage.warning("没有符合条件的物资种类二维码标签");
    return;
  }
};
// 详情物资类型详情
const handleView = (row: any) => {
  dialogType.value = "view";
  rowData.value = row;
  dialogVisibleView.value = true;
};
// 复制物资管理
const handleCopy = (row: any) => {
  dialogType.value = "copy";
  rowData.value = row;
  dialogVisible.value = true;
};

// 编辑单条物资类型
const handleEdit = (row: any) => {
  dialogType.value = "edit";
  rowData.value = row;
  dialogVisible.value = true;
};
// 删除单条物资类型
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`要删除当前物资“${row.name}”吗？删除后不可恢复，请谨慎操作`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const eqpIdListsPuls = [];
      eqpIdListsPuls.push(row.id);
      await deleteToolMaterial({
        idList: eqpIdListsPuls
      });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-flex-list.scss");

.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;
}

.buttonGroup {
  display: flex;
  margin-right: 8px;
}

:deep(.px-scrollbar__bar.is-horizontal) {
  height: 12px; /* 增加滚动条厚度 */
}

:deep(.pagination-container) {
  padding: 16px 20px !important;
  margin-top: 0;
  margin-bottom: 10px;
}
</style>
